# _*_ coding:utf-8 _*_
# @Time  : 2023.05.29
# @Author: zizlee
import random
import hashlib
import time

from passlib.context import CryptContext


class Encrypt:
    # deprecated="auto"文档解释：自动将列表中除第一个哈希程序外的所有哈希程序标记为已弃用(2.0版默认值)。(不懂什么意思)
    PWD_CONTEXT = CryptContext(schemes=['bcrypt'], deprecated="auto")

    @classmethod
    def random_string(cls, length=6, use_hash=True):
        string_pool = 'abcdefghijklmnopqrstuvwxyz123456789'
        ret_string = ''
        for _ in range(length):
            ret_string += random.choice(string_pool)
        if use_hash:
            h = hashlib.md5(ret_string.encode('utf8'))
            h.update(str(time.time_ns()).encode('utf8'))
            hash_string = ''
            for _ in range(length):
                hash_string += random.choice(h.hexdigest())
            ret_string = hash_string
        return ret_string

    @classmethod
    def password_hash(cls, password):
        return cls.PWD_CONTEXT.hash(password)

    @classmethod
    def password_verify(cls, password_plain, password_hash):
        return cls.PWD_CONTEXT.verify(password_plain, password_hash)

    @classmethod
    def md5_hash(cls, plain: str, length=32):
        return hashlib.md5(plain.encode('utf8')).hexdigest()[:length]

